<template>
	<div class="system-user-dialog-container energy-from energy-dialog energy-tree">
		<el-dialog center align-center v-model="state.dialog.isShowDialog" width="769px" @close="resetData">
			<template #header="{ titleClass }">
				<div :class="titleClass">
					{{ state.dialog.title }}
				</div>
			</template>
			<el-form ref="userDialogFormRef" :model="state.ruleForm" :rules="state.rules" size="default" label-width="120px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="套餐名称" prop="name">
							<el-input v-model="state.ruleForm.name" :disabled="state.dialog.type == 'isDetail'" placeholder="请输入套餐包名称" clearable></el-input>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="套餐状态" prop="status">
							<el-switch
								v-model="state.ruleForm.status"
								size="default"
								:active-value="0"
								:inactive-value="1"
								active-text="启用"
								inactive-text="禁用"
								inline-prompt
								style="--el-switch-on-color: #13ce66"
								:disabled="state.dialog.type == 'isDetail'"
							/>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="功能配置" prop="menuIds">
							<el-tree
								ref="treeRef"
								:data="state.allMenuData"
								:props="state.menuProps"
								node-key="id"
								:default-checked-keys="state.defaultChecked"
								:default-expanded-keys="state.defaultChecked"
								show-checkbox
								check-strictly
								class="menu-data-tree"
								@check="handleCheck"
							/>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="备注">
							<el-input
								v-model="state.ruleForm.remark"
								placeholder="请输入备注"
								clearable
								type="textarea"
								:disabled="state.dialog.type == 'isDetail'"
							>
							</el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div class="flex row-center mt10 mb10">
				<div class="btn3" @click="onCancel">
					<el-icon> <ele-Close /> </el-icon><span class="ml6">关 闭</span>
				</div>
				<div class="btn1 ml10" @click="onSubmit()" v-if="state.dialog.type !== 'isDetail'">
					<el-icon> <ele-Check /> </el-icon><span class="ml6">保 存</span>
				</div>
			</div>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import { reactive, ref, nextTick } from 'vue';
import { usePackageApi } from '/@/api/system/package';
import { useMenuApi } from '/@/api/menu';
import { ElNotification } from 'element-plus';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
const treeRef = ref();
// 定义变量内容
const userDialogFormRef = ref();
const state: any = reactive({
	ruleForm: {
		id: '',
		name: '', // 套餐名
		status: 0, // 状态（0正常 1停用）
		remark: '', // 备注
		menuIds: [], // 权限菜单id
	},
	allMenuData: [], // 所有菜单权限
	defaultChecked: [], // 默认选中的id集合
	menuProps: {
		children: 'childList',
		label: 'title',
		disabled: 'disabled',
	},
	dialog: {
		isShowDialog: false,
		title: '',
		type: '',
	},
	rules: {
		name: [{ required: true, message: '请输入套餐包名称', trigger: 'blur' }],
		status: [{ required: true, message: '请选择套餐状态', trigger: 'change' }],
		menuIds: [{ required: true, message: '请选择套餐功能配置', trigger: 'change' }],
	},
});

// 打开弹窗
const openDialog = (row: any, type: string) => {
	if (type == 'isAdd') {
		state.dialog.title = '新增套餐';
		getALLMenuData();
	} else {
		state.dialog.title = type === 'isEdit' ? '修改套餐' : '查看套餐详情';
		state.ruleForm.id = row.id;
		state.ruleForm.name = row.name;
		state.ruleForm.status = row.status;
		state.ruleForm.remark = row.remark;
		getPackagePermission(row.id);
	}
	state.dialog.type = type;
	state.dialog.isShowDialog = true;
};

// 获取所有权限数据-筛选出菜单
const getALLMenuData = async () => {
	const { data } = await useMenuApi().getAllMenu();
	state.allMenuData = filterMenu(data);
};

// 过滤掉按钮权限
const filterMenu = (row: any[]) => {
	let result: any = [];
	row.forEach((item: any) => {
		if (item.type === 1) {
			if (item.childList && item.childList.length > 0) {
				result.push({
					id: item.id,
					title: item.title,
					childList: filterMenu(item.childList),
					disabled: 0,
				});
			} else {
				result.push({
					id: item.id,
					title: item.title,
					childList: [],
					disabled: 0,
				});
			}
		}
	});
	return result;
};

// 获取套餐权限菜单
const getPackagePermission = async (id: string) => {
	const { data } = await usePackageApi().getModulePackage(id);
	state.allMenuData = [...data.menus];

	let tileData: any = [];
	function changMenuData(data: []) {
		data.forEach((item: any) => {
			item.disabled = state.dialog.type == 'isDetail' ? 1 : 0;
			tileData.push(item);
			if (item.childList && item.childList.length > 0) {
				changMenuData(item.childList);
			}
		});
	}
	changMenuData(data.menus);

	state.defaultChecked = [];
	tileData.map((item: any) => {
		if (item.selected == 1) {
			state.defaultChecked.push(item.id);
		}
	});

	nextTick(() => {
		handleCheck();
	});
};

//获取选中的数据
const handleCheck = () => {
	// 树形数据扁平化
	let newTileData: any = [];
	function changMenuData(data: []) {
		data.forEach((item: any) => {
			newTileData.push(item);
			if (item.childList && item.childList.length > 0) {
				changMenuData(item.childList);
			}
		});
	}
	changMenuData(state.allMenuData);

	// 过滤出需要的数据
	state.ruleForm.menuIds = [];
	newTileData.map((i: any) => {
		treeRef.value.getCheckedNodes().map((item: any) => {
			if (i.id == item.id) {
				state.ruleForm.menuIds.push(item.id);
			}
		});
	});
};

// 提交
const onSubmit = () => {
	userDialogFormRef.value.validate((valid: any) => {
		if (valid) {
			state.dialog.type == 'isAdd' ? doAdd() : doEdit();
		} else {
			ElNotification({
				title: '提示',
				message: '校验失败,请填写完整用户信息',
				position: 'top-right',
				type: 'error',
			});
		}
		closeDialog();
	});
};

// 新增套餐
const doAdd = async () => {
	const data = await usePackageApi().addModulePackage(state.ruleForm);
	if (data.code == 200) {
		emit('refresh');
		ElNotification({
			title: '提示',
			message: '分配权限成功',
			position: 'top-right',
			type: 'success',
		});
	}
};

// 编辑套餐
const doEdit = async () => {
	const data = await usePackageApi().updatePackage(state.ruleForm);
	if (data.code == 200) {
		emit('refresh');
		ElNotification({
			title: '提示',
			message: '分配权限成功',
			position: 'top-right',
			type: 'success',
		});
	}
};

// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};

// 取消
const onCancel = () => {
	closeDialog();
};

// 表单清空
const resetData = () => {
	userDialogFormRef.value.resetFields();
	state.allMenuData = [];
	state.defaultChecked = [];

	state.ruleForm = {
		id: '',
		name: '', // 套餐名
		status: 0, // 状态（0正常 1停用）
		remark: '', // 备注
		menuIds: [], // 权限菜单id
	};
};

// 暴露变量
defineExpose({
	openDialog,
});
</script>
<style scoped lang="scss"></style>
